package com.example.t470p.facechecktickets.View;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.t470p.facechecktickets.BaseUrl;
import com.example.t470p.facechecktickets.M1CardInfo;
import com.example.t470p.facechecktickets.PopListAdapter;
import com.example.t470p.facechecktickets.R;
import com.example.t470p.facechecktickets.ResultCode;
import com.example.t470p.facechecktickets.Utils.LogUtil;
import com.example.t470p.facechecktickets.Utils.ToastUtil;
import com.example.t470p.facechecktickets.Utils.base64;
import com.example.t470p.facechecktickets.Utils.pathUtils;
import com.example.t470p.facechecktickets.Utils.signUtils;
import com.example.t470p.facechecktickets.httpUtils;
import com.example.t470p.facechecktickets.response.GateListResponse;
import com.example.t470p.facechecktickets.response.ICCardCheckResponse;
import com.example.t470p.facechecktickets.response.ICCardCollectionResponse;
import com.example.t470p.facechecktickets.response.QRCodeCheckResponse;
import com.example.t470p.facechecktickets.response.QRCodeCollectionResponse;
import com.example.t470p.facechecktickets.response.TicketOrCardResponse;
import com.google.gson.Gson;
import com.synjones.handsetS8.BarReaderModule;
import com.synjones.handsetS8.BarScanResult;
import com.synjones.handsetS8.IDCardReaderModule;
import com.synjones.idcard.IDCard;
import com.synjones.idcard.IDCardReaderRetInfo;
import com.synjones.m1card.M1CardReader;
import com.synjones.multireaderlib.MultiReader;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;


import com.example.t470p.facechecktickets.PictureFaceMatch.TakePhotoActivity;
import com.example.t470p.facechecktickets.Utils.util;
import com.example.t470p.facechecktickets.facesdk.FaceAuthAsync;
import com.example.t470p.facechecktickets.facesdk.FaceHandle;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;

import static com.example.t470p.facechecktickets.Utils.xmlUtil.getxmlstr;

public class CheckActivity extends Activity implements View.OnClickListener {

    /*************************初始化***********************/
    public TextView m_Status;
    private ImageView m_imageViewPhoto;
    public TextView m_CardNo;
    public TextView m_Date;

    public Button m_btnReadCard;
    public Button m_btnFaceDetect;
    public Button m_btnBarSacn;
    public Button m_btnOk;
    public boolean m_bNeedFaceDetect = false;         //是否需要人脸识别
    public String m_Url;
    public String m_strStatus;
    public String m_strCardNo;
    public String m_strDate;
//    public String m_strGateNo = MyApplication.m_strGateNo;
    public String m_strGateNo ;
    public String m_strTicketNo;

    public int mode_0 = 0;  //http工作模式检票,0:获取图片
    public int mode_1 = 1;  //http工作模式检票,1:检票
    public int m_CheckMode;                          //1:检卡 2:检票
    public int type_QRCode = 1; //二维码卡号
    public int type_IDCard = 2; //身份证卡号
    public int type_ICCard = 3; //IC卡号
    public int tag_compare = 0;
    /****************************************************/
    /************************M1卡************************/
    boolean findingCard = false;
    private byte data[] = new byte[1024];//接收buf
    private int dataLen = 0;//接收数据长度
    IDCardReaderModule idCardReaderModule;
    public M1CardReader m1Reader;
    MultiReader multiReader;
    boolean isConnect;
    final int MESSAGE_FIND_CARD = 0x51;
    String m_strM1Card; //IC 卡号
    int ticketCount = 0; //检票计数


    TicketOrCardResponse response;
    QRCodeCollectionResponse qrCodeCollectionResponse;
    ICCardCollectionResponse cardCollectionResponse;

    //添加sharePreferce用于保存密码和登录
    private SharedPreferences pref;
    private SharedPreferences.Editor editor;
    int saveDate, currentDate;
    // 使用默认时区和语言环境获得一个日历
    Calendar cal = Calendar.getInstance();

    public final  int COLLECT_INFORMATION=9;
    public final  int COMPARE_FACE=10;
    private static final int ReadOnceDone=12;
    private static final int ReadThreadDone=13;

    GateListResponse gateListResponse;
    List<GateListResponse.GateInfoListBean> list;
    public static  final  int CHECK_SUCCESS=1;


    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case MESSAGE_FIND_CARD:
                    if (data == null)
                        return;
                    // beep();
                    //Toast.makeText(activity, "find a Card", Toast.LENGTH_SHORT).show();
                    if (dataLen != 0) {

                        M1CardInfo m1CardInfo = new M1CardInfo(data);
                        String lM1CardNo = m1CardInfo.getCardNoStr();

                        lM1CardNo = lM1CardNo.replace("0x", "");

                        //lM1CardNo = lM1CardNo.replace(",","");

                        //翻转字符串
                        lM1CardNo = ReserveHexStr(lM1CardNo);
                        //16进制字符串转10进制字符串
                        m_strM1Card = new BigInteger(lM1CardNo, 16).toString();

                        m_bNeedFaceDetect = true;
                        //从服务器获取图片
//                        GetImgFromServer(m_strM1Card);

                        checkCard_or_Ticket(type_ICCard, m_strM1Card);

                        ShowMsg(m_strM1Card, 1, 0);

                        m_btnReadCard.setEnabled(true);
                        m_btnBarSacn.setEnabled(true);
                    } else {
                        m_btnReadCard.setEnabled(true);
                        m_btnBarSacn.setEnabled(true);
                        ShowMsg("读取失败", 0, 0);
                    }

                    break;
                case CHECK_SUCCESS:

                    ticketCount = ticketCount + (int)msg.obj;
                    tv_count.setText("" + ticketCount);
                    break;

                case COLLECT_INFORMATION:
//                    qrCompare();
                    qrCollection();
                    break;
                case COMPARE_FACE:
                    int tag=Integer.valueOf(msg.obj.toString());
                    if ( tag==type_QRCode) {
                        getQRCodeCollection(m_StrBarCode);
                    }else if (tag==type_ICCard){
                        getCheckCardCollection(m_strM1Card);
                    }
                    break;
                case ReadOnceDone:

                    IDCard idcard=(IDCard)msg.obj;
                    if (idcard!=null) {
//                        try {
//                            //int result = idcard.decodeResult;
//                            if(bmp!=null) bmp.recycle();
//                            bmp=idcard.getPhoto();
////                            bmp=pathUtils.GetBitmapByPath(m_FaceImgPath);
//                            if (bmp !=null) {//保存照片
//                                //MediaStore.Images.Media.insertImage(getContentResolver(), bmp, "zp", "");
//                                //String bmpPath = getFileStreamPath("photo.bmp").getAbsolutePath();
//                                //util_File.copyfile(bmpPath,util_File.getExternalPath()+idcard.getName()+".bmp");
//                            } else {
//                                Resources res = getResources();
//                                bmp = BitmapFactory.decodeResource(res, R.drawable.photo);
//                            }
//                            m_imageViewPhoto.setImageBitmap(bmp);
//                            m_imageViewPhoto.post(new Runnable() {
//                                @Override
//                                public void run() {
//                                    m_imageViewPhoto.setImageBitmap(bmp);
//                                }
//                            });
//
//                            System.gc();
//                        } catch (Exception ioe) {
//                            ToastUtil.showToast("照片异常:"+ioe.toString());
//                        }
                        m_CardNo.setText(idcard.getIDCardNo());     //读卡成功，显示身份证信息
                        checkCard_or_Ticket(type_IDCard, idcard.getIDCardNo());
                    }else {
                        ShowMsg("身份证读取失败",0,0);
                    }
                    CloseReader();//停止读取身份证
                    break;
            }
        }
    };
    private ImageView img_bind;
    private boolean isGateSet;
    private PopupWindow popupWindow;
    private int screenWidth,screenHeight;
    private boolean isCheck;


    private boolean reading=false;
    private long StartTime;
    private String status="";

    private ReadCardThread ReadCardThreadhandler;
    private Bitmap bmp;

//    private void qrCompare() {
//        m_bFaceDetectResult = false;
//        m_FaceBmp = pathUtils.GetBitmapByPath(m_FaceImgPath);
//        if (m_FaceBmp == null) {
//            Toast.makeText(this, "人脸比对请先读卡", Toast.LENGTH_SHORT).show();
//            return;
//        }
//        Intent intent = new Intent(this, TakePhotoActivity.class);
//        //Intent intent = new Intent(MainActivity.this,FaceTestActivity.class); //动态识别版 仅适用于V1算法
//        TakePhotoActivity.img = util.bitmap2ByteArray(m_FaceBmp);
//        intent.putExtra("ALGORITHM_VERSION", ALGORITHM_VERSION);
//        //intent.putExtra("WORKINGMODE",1);
//        intent.putExtra("WORKINGMODE", 1);
//        startActivityForResult(intent, 0);
//    }

    private void qrCollection() {
        Intent intent = new Intent(this, TakePhotoActivity.class);
        //Intent intent = new Intent(MainActivity.this,FaceTestActivity.class); //动态识别版 仅适用于V1算法
        m_BGBmp = pathUtils.GetBitmapByPath(m_BgFacePath);
        TakePhotoActivity.img = util.bitmap2ByteArray(m_BGBmp);
        intent.putExtra("ALGORITHM_VERSION", ALGORITHM_VERSION);
        intent.putExtra("WORKINGMODE", 2);
        this.startActivityForResult(intent, 0);

    }


    //    0--------接口调用成功,即检票成功
    /****************************************************/

    /**********************人脸识别**********************/
    public static final int ALGORITHM_VERSION = 1;
    private Bitmap m_FaceBmp;
    public Bitmap m_BGBmp;
    String m_FaceImgPath;
    String m_BgFacePath;
    boolean m_bFaceDetectResult = false;    //false:失败,true:成功
    /****************************************************/

    /************************扫码************************/
    BarReaderModule barReaderModule;             //扫描头
    public boolean bNeedCheckTicket = true;    //检票标志位
    private String m_StrBarCode;                //二维码号码
    public String m_UpdateBase64;              //上传的Base64图片
    public String m_UpdatePhotoPath;          //采集上传的图片路径
    public String m_UpdatePhotoName;          //采集上传的图片名称
    public String m_UpdateImgPath;            //需要上传的图片路径
    private TextView tv_count;




    /****************************************************/

    /**********************语音合成**********************/
    //语音引擎
    private class TTSListener implements TextToSpeech.OnInitListener {
        @Override
        public void onInit(int status) {
            // TODO Auto-generated method stub
            if (status == TextToSpeech.SUCCESS) {
                /*
               int supported = mSpeech.setLanguage(Locale.ENGLISH);
                if ((supported != TextToSpeech.LANG_AVAILABLE) && (supported != TextToSpeech.LANG_COUNTRY_AVAILABLE)) {
                   Toast.makeText(MainActivity.this, "不支持当前语言！", Toast.LENGTH_SHORT).show();
                   Log.i(TAG, "onInit: 支持当前选择语言");
               }else{

               }
               */
                Log.i(TAG, "onInit: TTS引擎初始化成功");
            } else {
                Log.i(TAG, "onInit: TTS引擎初始化失败");
            }
        }
    }

    private static final String TAG = "CheckActivity";
    private TextToSpeech mSpeech = null;
    private static float m_voice_speed = 1.0f;   //合成语音的语速
    private static float m_voice_pitch = 1.0f;   //合成语音的语调

    /****************************************************/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        //取消标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //取消状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_check);

        pref = getSharedPreferences("data", Context.MODE_PRIVATE);
        editor = pref.edit();
        Init();
        isGateSet=pref.getBoolean("isGateSet",false);
        if (isGateSet) {
             m_strGateNo = pref.getString("gateNo","0");
        }else {
           ToastUtil.showToast("请配置闸机");
        }
        getGateList();
    }

    /*
     * 初始化
     */
    public void Init() {
        WindowManager manager = (WindowManager) getBaseContext().getSystemService(Context.WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        Point point = new Point();
        if (Build.VERSION.SDK_INT < 17) {
            display.getSize(point);
        } else {
            display.getRealSize(point);
        }
        screenWidth = point.x;
        screenHeight = point.y;
        m_Status = (TextView) findViewById(R.id.StatusMsg);

        m_CardNo = (TextView) findViewById(R.id.CardNo);
        m_Date = (TextView) findViewById(R.id.date);
        m_imageViewPhoto = (ImageView) findViewById(R.id.imageViewPhoto);

        m_btnReadCard = (Button) findViewById(R.id.btnReadCard);
        m_btnFaceDetect = (Button) findViewById(R.id.btnFaceDetect);
        m_btnBarSacn = (Button) findViewById(R.id.btnScan);
        m_btnOk = (Button) findViewById(R.id.btnOk);

        img_bind = (ImageView) findViewById(R.id.ca_img_bind);
        img_bind.setOnClickListener(this);
        tv_count = (TextView) findViewById(R.id.tv_Count);

        saveDate = pref.getInt("saveDate", 0);
        ticketCount = pref.getInt("ticketCount", 0);
        currentDate = cal.get(Calendar.DAY_OF_MONTH);
        //和当前日期不一致，清空票数
        if (saveDate != currentDate) {
            Log.d("date", "" + "clear data");
            ticketCount = 0;
        } else {
            Log.d("date", "" + "count");
        }
        tv_count.setText("" + ticketCount);


        m_btnReadCard.setEnabled(true);
        m_btnFaceDetect.setEnabled(false);
        m_btnBarSacn.setEnabled(true);
//        m_btnOk.setEnabled(false);
        m_btnOk.setEnabled(true);


        //M1卡初始化
        idCardReaderModule = IDCardReaderModule.getInstance(this);
        multiReader = idCardReaderModule.getBaseMultiReader();
        isConnect = idCardReaderModule.isOpen();
        if (!isConnect) {
            idCardReaderModule.open();
        }
        isConnect = idCardReaderModule.isOpen();
        if (null == m1Reader) {
            m1Reader = new M1CardReader(multiReader);
        }
        m_bNeedFaceDetect = false;


        m_CheckMode = 1;

        //人脸初始化
        //图片路径
        m_FaceImgPath = pathUtils.getSDPath() + "/FaceCheck.png";

        m_BgFacePath = pathUtils.getSDPath() + "/BGFace.bmp";

        new FaceAuthAsync(this, FaceHandle.getFaceSDKInstance(ALGORITHM_VERSION)).setOnfinish(new FaceAuthAsync.OnFinish() {
            @Override
            public void onDone(boolean initOk, int errCode) {
                if (!initOk)
                    Toast.makeText(CheckActivity.this, "人脸初始化错误，errcode=" + errCode, Toast.LENGTH_SHORT).show();
            }
        }).execute();
        //扫描头初始化
        m_StrBarCode = "";
        barReaderModule = BarReaderModule.getInstance(this);
        barReaderModule.open();

        m_UpdateImgPath = pathUtils.getSDPath() + "/UpdateImg.jpg";
        //获取TTS引擎
        mSpeech = new TextToSpeech(CheckActivity.this, new TTSListener());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ca_img_bind:

                View view = View.inflate(this, R.layout.popupwindow_ma_layout, null); //引入布局
                //获取PopupWindow中View的宽高
                view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);


                //将布局view传参给popupwindow
                popupWindow = new PopupWindow(view, screenWidth, screenHeight * 3 / 5);
                popupWindow.setBackgroundDrawable(new ColorDrawable(0xaa000000));//设置背景

                popupWindow.setFocusable(true);//popupwindow设置焦点
                popupWindow.setOutsideTouchable(true);//点击外面窗口消失
                popupWindow.showAtLocation(v, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

                setOnPopupViewClick(view);
                popupWindow.setAnimationStyle(android.R.style.Animation_Translucent);//设置动画

                break;
        }

    }
    private void getGateList() {

        String url = BaseUrl.BaseHttp + BaseUrl.UNBINDPHONELIST;
        OkHttpUtils
                .get()
                .url(url)
                .addParams("userName", "admin")
                .addParams("password", "888888")
                .addParams("sign", "DDCA01EF3FF8B6C429D8FE406740539F")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastUtil.showToast(e.toString());
                    }

                    @Override
                    public void onResponse(String response, int id) {

                        try {
                            gateListResponse = new Gson().fromJson(response, GateListResponse.class);
                            if (gateListResponse.getCode().equals("0")) {

                                list = gateListResponse.getGateInfoList();

                            } else {
                                ToastUtil.showToast("" + gateListResponse.getMessage());
                            }
                        } catch (Exception e) {
                            ToastUtil.showToast("" + e.toString());

                        }
                    }

                });
    }
    private void setOnPopupViewClick(View view) {

        ImageView img_close = (ImageView) view.findViewById(R.id.pop_img_close);
        ListView pop_list = (ListView) view.findViewById(R.id.pop_list);
        final PopListAdapter adapter;
        if (null != list && list.size()>0) {
            adapter = new PopListAdapter(getBaseContext(), list);
            pop_list.setAdapter(adapter);
        }else {
          ToastUtil.showToast("闸机列表为空");
            return;
        }

        img_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        pop_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                editor.putInt("position", position);
                editor.putString("gateName", list.get(position).getGateName());
                editor.putString("gateNo", list.get(position).getGateNo());
                m_strGateNo=list.get(position).getGateNo();
                isGateSet=true;
                editor.putBoolean("isGateSet",true);
                editor.commit();
                adapter.notifyDataSetChanged();
                ToastUtil.showToast("选中"+list.get(position).getGateName()+"成功");

            }
        });
    }
    @Override
    protected void onPause() {
        super.onPause();
//        处理保存票数和当前日期
        int saveDate = cal.get(Calendar.DAY_OF_MONTH);
        editor.putInt("saveDate", saveDate);
        editor.putInt("ticketCount", ticketCount);
        editor.commit();
    }


    //播放合成语音
    public void PlayAudioFile(String str) {
        //设置中文
        int supported = mSpeech.setLanguage(Locale.CHINESE);
        mSpeech.setSpeechRate(m_voice_speed);
        mSpeech.setPitch(m_voice_pitch);

        if ((supported != TextToSpeech.LANG_AVAILABLE) && (supported != TextToSpeech.LANG_COUNTRY_AVAILABLE)) {
            //语言设置失败
            Log.i(TAG, "中文设置失败");
        } else {
            Log.i(TAG, "中文设置成功");
        }
        //mSpeech.speak(str, TextToSpeech.QUEUE_FLUSH, null);
        mSpeech.speak(str, TextToSpeech.QUEUE_ADD, null);
    }

    /*
     * 读取身份证
     */
    public void BtnIDCardOnClick(View view) {

//        if (!isGateSet){
//            ToastUtil.showToast("请配置闸机");
//            return;
//        }

        if(reading==false)
        {
            ShowMsg("请稍等", 0, 0);
            startReadThread();
        }
    }
    void startReadThread(){

        StartTime=0;
        reading=true;
        ReadCardThreadhandler=new ReadCardThread();
        ReadCardThreadhandler.start();
    }
    /**
     * 打开读卡器
     * @Title OpenReader
     */
    private void OpenReader(){
        if(!idCardReaderModule.isOpen())
            idCardReaderModule.open();
    }

    //读卡线程
    class ReadCardThread extends Thread{
        public void run() {
            OpenReader();
            long t=System.currentTimeMillis();
            while (reading){//读卡器上电需要时间，通过获取samvid判断读卡器是否已工作
                String samvID=idCardReaderModule.getSamvIDString();
                if(samvID!=null && samvID.length()>0)
                    break;
                util.sleep(50);//如果超时，则重新打开读卡器
                if(System.currentTimeMillis()-t>2000){
                    t=System.currentTimeMillis();
                    idCardReaderModule.close();
                    idCardReaderModule.open();
                }
            }

            StartTime=System.currentTimeMillis();
//            UpdateTimerThread utt=new UpdateTimerThread();
//            utt.start();
            while(reading)
            {
                try{
                    //getIDcardInfo()只读身份证信息，不读取指纹信息。 等同于getIDcardInfo(false, true, false);
                    IDCardReaderRetInfo retInfo;
//                    if(!boolReadFringerprint)//是否需要读指纹
                        retInfo = idCardReaderModule.getIDcardInfo();
//                    else
//                        retInfo = idCardReaderModule.getIDcardInfo(false,true,true);

                    //读取指纹信息，读卡时间会稍长  可参考指纹的activity中读取身份证指纹按钮的实现
                    //IDCardReaderRetInfo retInfo = idCardReaderModule.getIDcardInfo(boolSameCardReadOnce, boolDecodePhoto, boolReadFringerprint);
                    //samvID=idCardReaderModule.getSamvIDString();//获取公安部二代证模块编号
                    //String appendAddress=idCardReaderModule.getAppendAddress();//获取身份证内的追加地址信息
                    if(retInfo.errCode==IDCardReaderRetInfo.ERROR_OK) {
//                        if(boolReadFringerprint) {//仅测试时读取追加信息
//                            retInfo.card.setAppendAddress(idCardReaderModule.getAppendAddress());
//                        }
                        mHandler.obtainMessage(ReadOnceDone,retInfo.card).sendToTarget();
                        status="";
                        Thread.sleep(500);
                    }
                    else{
                        status=util.bytesToHexString(new byte[]{retInfo.sw1,retInfo.sw2,retInfo.sw3});
                        mHandler.obtainMessage(ReadOnceDone,null).sendToTarget();
                        Thread.sleep(200);
                    }

                }catch (Exception e) {
                    e.printStackTrace();
                }
            }//while

//            mHandler.obtainMessage(ReadThreadDone).sendToTarget();

        }//run

        public void StopRead(){
            reading=false;
            interrupted();
            try {
                join(500);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }
    /**
     * 关闭读卡器
     * @Title CloseReader
     */
    private void CloseReader(){
        //停止读卡线程
        if(ReadCardThreadhandler!=null){
            ReadCardThreadhandler.StopRead();
            ReadCardThreadhandler=null;
        }
        idCardReaderModule.close();
    }
    /*
     * 刷卡按钮点击函数
     */
    public void BtnReadCardOnClick(View v) {

//        if (!isGateSet){
//            ToastUtil.showToast("请配置闸机");
//            return;
//        }

        m_CheckMode = 1;
        m_BGBmp = pathUtils.GetBitmapByPath(m_BgFacePath);
        m_imageViewPhoto.post(new Runnable() {
            @Override
            public void run() {
                m_imageViewPhoto.setImageBitmap(m_BGBmp);
            }
        });
        ShowMsg("请稍等", 0, 0);
        ShowMsg("", 1, 0);
        ShowMsg("", 2, 0);
        m_btnReadCard.setEnabled(false);
        //开启人脸识别
        m_btnFaceDetect.setEnabled(false);
        m_btnBarSacn.setEnabled(true);
//        m_btnOk.setEnabled(false);
        m_btnOk.setEnabled(true);
        FindCard(3000);
    }

    /*
     * 人脸核验按钮点击函数
     */
    public void BtnFaceDetectOnClick(View v) {

        if (!isGateSet){
            ToastUtil.showToast("请配置闸机");
            return;
        }

        m_bFaceDetectResult = false;
        m_FaceBmp = pathUtils.GetBitmapByPath(m_FaceImgPath);
        if (m_FaceBmp == null) {
            Toast.makeText(this, "人脸比对请先读卡", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent(this, TakePhotoActivity.class);
        //Intent intent = new Intent(MainActivity.this,FaceTestActivity.class); //动态识别版 仅适用于V1算法
        TakePhotoActivity.img = util.bitmap2ByteArray(m_FaceBmp);
        intent.putExtra("ALGORITHM_VERSION", ALGORITHM_VERSION);
        //intent.putExtra("WORKINGMODE",1);
        intent.putExtra("WORKINGMODE", 1);
        startActivityForResult(intent, 0);
        m_btnReadCard.setEnabled(false);

        // m_btnFaceDetect.setEnabled(false);
        m_btnBarSacn.setEnabled(false);
        m_btnOk.setEnabled(false);

    }


    /*
     * 扫码按钮点击函数
     */
    public void BtnScanOnClick(View v) {

//        if (!isGateSet){
//            ToastUtil.showToast("请配置闸机");
//            return;
//        }

        m_CheckMode = 2;
        m_imageViewPhoto.post(new Runnable() {
            @Override
            public void run() {
                m_imageViewPhoto.setImageBitmap(m_BGBmp);
            }
        });
        ShowMsg("请稍等", 0, 0);
        //清空显示
        ShowMsg("", 1, 0);
        ShowMsg("", 2, 0);
        m_btnReadCard.setEnabled(false);

        m_btnBarSacn.setEnabled(false);
        m_btnOk.setEnabled(false);
        barReaderModule.scan(new BarReaderModule.OnScanResult() {
            @Override
            public void onScanResult(BarScanResult barScanResult) {
                if (barScanResult.code != 0) {
                    ShowMsg("扫码失败", 0, 0);
                    m_btnReadCard.setEnabled(true);
                    m_btnBarSacn.setEnabled(true);
                    return;
                } else {

                    int end_pos = barScanResult.barMsg.lastIndexOf("\r\n");

                    if (0 > end_pos) {
                        m_StrBarCode = barScanResult.barMsg;
                    } else {
                        m_StrBarCode = barScanResult.barMsg.substring(0, end_pos);
                    }
                    if (m_StrBarCode != null && !m_StrBarCode.equals("") && !m_StrBarCode.equals("0")) {
                        ShowMsg(m_StrBarCode, 1, 0);
                        //ShowMsg("扫码成功",0,0);
                        //检票(二维码)
//                        CheckBarCodeTicket();
                        m_StrBarCode = m_StrBarCode.replaceAll("\r|\n", "");
                        checkCard_or_Ticket(type_QRCode, m_StrBarCode);
                        Log.d(TAG, "onScanResult: 扫码成功");

                    } else {
                        ShowMsg("扫码为空", 0, 0);
                        bNeedCheckTicket = true;
                        m_btnReadCard.setEnabled(true);
                        m_btnBarSacn.setEnabled(true);
                    }
                }
            }
        });
    }

    /*
     * 人工确认按钮点击函数
     */
    public void BtnOkOnClick(View v) {

        if (!isGateSet){
            ToastUtil.showToast("请配置闸机");
            return;
        }

        m_btnOk.setEnabled(true);
        //检票
//        CheckTickets();
        if (tag_compare == 0) {
            if ("".equals(m_strM1Card)||isCheck==false) {
                ToastUtil.showToast("请先读取IC卡");
                return;
            }
            if (null==response.getData().getCardBarcodeId()) {
                ToastUtil.showToast("不满足人工判断条件");
                return;
            }
            checkCardAfterCompare(m_strM1Card);
        } else {
            if ("".equals(m_StrBarCode)||isCheck==false) {
                ToastUtil.showToast("请先读取二维码");
                return;
            }
            if (null==response.getData().getTicketBarcodeId()) {
                ToastUtil.showToast("不满足人工判断条件");
                return;
            }
            checkTicketAfterCompare(m_StrBarCode);
        }

    }

    /*
     * 显示信息(0:Status,1:CardNo,2:Date)
     */
    public void ShowMsg(String Msg, int type, int PlayOrNot) {
        switch (type) {
            case 0:
                m_strStatus = Msg;
                if (0 == PlayOrNot) {
                    //播放声音
                    PlayAudioFile(Msg);
                }
                m_Status.post(new Runnable() {
                    @Override
                    public void run() {
                        m_Status.setText(m_strStatus);
                    }
                });
                break;
            case 1:
                m_strCardNo = Msg;
                m_CardNo.post(new Runnable() {
                    @Override
                    public void run() {
                        m_CardNo.setText(m_strCardNo);
                    }
                });
                break;
            case 2:
                m_strDate = Msg;
                m_Date.post(new Runnable() {
                    @Override
                    public void run() {
                        m_Date.setText(m_strDate);
                    }
                });
                break;
        }
    }

    /*
     * 设置按钮状态(0:false,1:true)
     */
    public void SetBtnEnable(int mode) {
        if (0 == mode) {
            m_btnReadCard.post(new Runnable() {
                @Override
                public void run() {
                    m_btnReadCard.setEnabled(false);
                }
            });

            m_btnBarSacn.post(new Runnable() {
                @Override
                public void run() {
                    m_btnBarSacn.setEnabled(false);
                }
            });
        } else {
            m_btnReadCard.post(new Runnable() {
                @Override
                public void run() {
                    m_btnReadCard.setEnabled(true);
                }
            });

            m_btnBarSacn.post(new Runnable() {
                @Override
                public void run() {
                    m_btnBarSacn.setEnabled(true);
                }
            });
        }
    }

    /*
     * Url字符转义
     */
    public String MyEncode(String str) {
        String ret = str.replace("+", "%20");
        ret = ret.replace("/", "%2F");
        ret = ret.replace("?", "%3F");
        ret = ret.replace("%", "%25");
        ret = ret.replace("#", "%23");
        ret = ret.replace("&", "%26");
        return ret;
    }

    /*
     * 16进制大小端调整
     */
    public String ReserveHexStr(String Hex) {
        String ret = "";
        int begin = 0;
        int end = Hex.indexOf(",", begin);
        List list = new ArrayList();
        while (true) {
            if (-1 == end) {
                break;
            }
            String test = Hex.substring(begin, end);
            list.add(test);
            begin = end + 1;
            end = Hex.indexOf(",", begin);
        }

        for (int index = list.size() - 1; index >= 0; index--) {
            if (index < 0) {
                break;
            }
            String ltest = list.get(index).toString();
            ret += ltest;
        }

        return ret;
    }

    /************************M1卡************************/
    /*
     * 调取接口获取照片信息(线程)
     */
    public void GetImgFromServer(String CardNo) {
        //测试
/*        Bitmap bitmap = GetBitmapByPath(m_FaceImgPath);
        m_imageViewPhoto.setImageBitmap(bitmap);*/
        //设置模式为获取图片
        HttpURL(mode_0);
    }

    /*
     * 检IC卡(线程)
     */
    public void CheckTickets() {
        //设置模式为检票
        HttpURL(mode_1);
    }

    /*
     * 检二维码(线程)
     */
    public void CheckBarCodeTicket() {
        //二维码检票
        BarCodeHttpURL();
    }

    /**
     * 寻卡
     */
    public void FindCard(final int timeout) {

        //M1卡初始化
        idCardReaderModule = IDCardReaderModule.getInstance(this);
        multiReader = idCardReaderModule.getBaseMultiReader();
        isConnect = idCardReaderModule.isOpen();
        if (!isConnect) {
            idCardReaderModule.open();
        }
        isConnect = idCardReaderModule.isOpen();
        if (null == m1Reader) {
            m1Reader = new M1CardReader(multiReader);
        }


        findingCard = true;
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                byte recv[] = null;
                int findTimes = 0;
                long t = System.currentTimeMillis();
                dataLen = 0;
                //multiReader.EnterWorkMode();
                while (findingCard && System.currentTimeMillis() - t < timeout && recv == null) {
                    recv = m1Reader.findM1Card();
                    if (recv != null) {
                        findTimes++;
                        if (findTimes >= 3) {//连续3次读卡成功 认为寻卡成功
                            System.arraycopy(recv, 0, data, 0, recv.length);
                            dataLen = recv.length;
                            mHandler.sendEmptyMessage(MESSAGE_FIND_CARD);
                            break;
                        }
                        recv = null;
                        util.sleep(10);
                    } else {
                        findTimes = 0;
                    }
                }
                findingCard = false;
                if (recv == null) {
                    mHandler.sendEmptyMessage(MESSAGE_FIND_CARD);
                }
            }
        }).start();
    }

    /**********************人脸识别**********************/
    /*
     * 重载onActivityResult(获取人脸页面返回值)
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        switch (resultCode) {
            case RESULT_OK:
                String result = data.getStringExtra("result");

                if (result.equals("COMPARESUCCESS")) {
                    m_bFaceDetectResult = true;
                    ShowMsg("核验成功", 0, 1);
                    //触发检票()
//                    CheckTickets();

                    if (tag_compare == 0) {
                        checkCardAfterCompare(m_strM1Card);
                    } else {
                        checkTicketAfterCompare(m_StrBarCode);
                    }

                    Log.d(TAG, "send: 4444444444444");
                }
                if (result.equals("COLLECTSUCCESS")) {
                    ShowMsg("正在上传请稍等", 0, 0);
                    //
                    m_bFaceDetectResult = true;
                    //读取图片并转成base64
//                    m_UpdateBase64 = base64.encodeBase64File(m_UpdateImgPath);
                    //Test
                    //decoderBase64File(m_UpdateBase64,getSDPath() + "/karlTest.jpg");
                    //toFile(m_UpdateBase64,getSDPath() + "/Base64.txt");
                    //m_UpdateBase64 = Uri.encode(m_UpdateBase64);

//                    m_UpdateBase64 = URLEncoder.encode(m_UpdateBase64);
//                    m_UpdateBase64 = base64.imageToBase64(m_UpdateImgPath);

                    m_UpdateBase64 = base64.imageToBase64Str(m_UpdateImgPath);
                    //上传采集片图片
//                    UpdateImgHttpURL();
                    uploadqrcodeInformation(m_StrBarCode);

                } else if (result.equals("COLLECTFAIL")) {
                    m_bFaceDetectResult = false;
                    //采集失败
                    ShowMsg("采集失败", 0, 1);
                    //m_btnReadCard.setEnabled(true);
                    m_btnFaceDetect.setEnabled(false);
                    m_btnBarSacn.setEnabled(true);
                } else {
                    m_bFaceDetectResult = false;
                    //显示失败并复原状态
                    ShowMsg("核验失败", 0, 1);
                    m_btnReadCard.setEnabled(true);
                    //m_btnFaceDetect.setEnabled(false);
                    //修改
                    m_btnFaceDetect.setEnabled(true);
                    m_btnBarSacn.setEnabled(true);
                }
                //finish();
                break;
            default:
                break;
        }//switch

    }//onActivityResult


    public  void setBtn(){
        m_btnFaceDetect.post(new Runnable() {
            @Override
            public void run() {
                m_btnFaceDetect.setEnabled(false);
            }
        }) ;
        m_btnReadCard.post(new Runnable() {
            @Override
            public void run() {
                m_btnReadCard.setEnabled(true);
            }
        });
        m_btnBarSacn.post(new Runnable() {
            @Override
            public void run() {
                m_btnBarSacn.setEnabled(true);
            }
        });
    }
    /*
     * 检票或检卡
     * */
    public void checkCard_or_Ticket(final int type, final String typeData) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                // 先封装一个 JSON 对象
                JSONObject param = new JSONObject();

                try {
                    param.put("searchDataType", type);
                    param.put("searchData", typeData);
                    param.put("checkCount", -1);
                    param.put("gateNo", m_strGateNo);
                    param.put("isCollectionGate", "Y");
                    param.put("sign", "A96D48AE69F46BD0E1B17F10316086F3");
                    param.put("timestamp", "20180611165000");


                String ss = httpUtils.postJson(BaseUrl.check_Ticket_or_Card, param);
                response = new Gson().fromJson(ss, TicketOrCardResponse.class);

                isCheck=true;
                int result1 = Integer.valueOf(response.getCode());
//                result = 100010;
                switch (result1) {
                    case ResultCode.SUCCESS:
                        int result= response.getData().getPassPersonSum();
                        Message message=new Message();
                        message.obj=result;
                        message.what=CHECK_SUCCESS;
                        mHandler.sendMessage(message);
                        ShowMsg(response.getData().getGateSoundName()+"可通行"+response.getData().getPassPersonSum()+"人", 0, 0);
                        setBtn();

                        break;
//                    case ResultCode.CHECKED:
//                        setBtn();
//                        ShowMsg(response.getData().getGateSoundName(), 0, 0);
//
//                        break;
//                    case ResultCode.SYSTEM_ERROR:
//                        setBtn();
//                        ShowMsg(response.getData().getGateSoundName(), 0, 0);
//                        break;
                    case ResultCode.TO_COLLECT_INFORMATION:

//                        LogUtil.d("采集信息");
//                        mHandler.sendEmptyMessage(COLLECT_INFORMATION);
                       ShowMsg("检票失败",0,0);
                        break;
                    case ResultCode.TO_COMPARE:
//                        LogUtil.d("人脸识别");
//                        Message msg =new Message();
//                        msg.obj = type;
//                        msg.what=COMPARE_FACE;   //标志消息的标志
//                        mHandler.sendMessage(msg);
                        ShowMsg("检票失败",0,0);
                        break;
//                    case ResultCode.CHECK_TIME_BETWEEN_IS_NOT_ENOUGH:
//                        setBtn();
//                        ShowMsg(response.getData().getGateSoundName(),0,0);
//                        break;
//                    case ResultCode.TIME_IS_INVAIBLE:
//                        setBtn();
//                        ShowMsg("不在运营时间内",0,0);
//                        break;
//                    case ResultCode.TIME_IS_INVAIBLE2:
//                        setBtn();
//                        ShowMsg("不在检票策略时间内",0,0);
//                        break;
//                    case ResultCode.UPLOAD_MESSAGE_FAIED:
//                        setBtn();
//                        ShowMsg("上传采集信息失败",0,0);
//                        break;
//                    case ResultCode.OUT_DATE:
//                        setBtn();
//                        ShowMsg("该票已过期",0,0);
//                        break;
//                    case ResultCode.QRCODE_IS_NOT_EXIST:
//                        setBtn();
//                        ShowMsg("该票不存在",0,0);
//                        break;
//                    case ResultCode.TODAY_COUNT_EXHAUST:
//                        setBtn();
//                        ShowMsg("当天次数已用完",0,0);
//                        break;
//                    case ResultCode.Card_IS_NOT_EXIST:
//                        setBtn();
//                        ShowMsg(response.getData().getGateSoundName(),0,0);
//                        break;
                        default:
                            setBtn();
                            ShowMsg(response.getData().getGateSoundName(),0,0);
                            ToastUtil.showToast(response.getMessage());
                            break;

                }
                } catch (Exception e) {
                    ToastUtil.showToast("checkCard_or_Ticket异常："+e.getMessage());
                }
            }
        }).start();

    }

    private void uploadqrcodeInformation(final String typeData) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 先封装一个 JSON 对象
                JSONObject param = new JSONObject();
                try {
                    param.put("searchDataType", 1);
                    param.put("searchData", typeData);
                    param.put("checkCount", -1);
                    param.put("gateNo", m_strGateNo);
                    param.put("isCollectionGate", "Y");
                    param.put("collectionDataType", "3");

                    param.put("barcodeNo", typeData);
                    param.put("ticketBarcodeId", response.getData().getTicketBarcodeId());
                    param.put("ticketValidTimes", response.getData().getTicketValidTimes());
                    param.put("ticketDayCounts", response.getData().getTicketDayCounts());
                    param.put("ticketTimeInterval", response.getData().getTicketTimeInterval());

                    param.put("sign", "A96D48AE69F46BD0E1B17F10316086F3");
                    param.put("timestamp", "20180611165000");
                    param.put("collectionDataInfo", m_UpdateBase64);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String ss = httpUtils.postJson(BaseUrl.check_Ticket_or_Card, param);
                LogUtil.d(ss);
                TicketOrCardResponse response2 = new Gson().fromJson(ss, TicketOrCardResponse.class);
                if (response2.getCode().equals("0")) {
                    ShowMsg("上传成功，请通行", 0, 0);
                    setBtn();
                    int result= response2.getData().getPassPersonSum();
                    Message message=new Message();
                    message.obj=result;
                    message.what=CHECK_SUCCESS;
                    mHandler.sendMessage(message);
                }else {
                    setBtn();
                    ShowMsg(response2.getData().getGateSoundName(),0,0);
                }

            }
        }).start();
    }
    /*
    * 人脸对比成功后检卡
    * */
    private void checkCardAfterCompare(final String typeData) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 先封装一个 JSON 对象
                JSONObject param = new JSONObject();
                try {
                    param.put("searchDataType", "3");
                    param.put("searchData", typeData);
                    param.put("checkCount", -1);
                    param.put("gateNo", m_strGateNo);
                    param.put("isCollectionGate", "Y");
                    param.put("cardBarcodeId", response.getData().getCardBarcodeId());
                    param.put("sign", "A96D48AE69F46BD0E1B17F10316086F3");
                    param.put("timestamp", "20180611165000");

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String ss = httpUtils.postJson(BaseUrl.checkCardAfterComparison, param);

                ICCardCheckResponse response = new Gson().fromJson(ss, ICCardCheckResponse.class);

                if (response.getCode().equals("0")) {
                    ShowMsg(response.getData().getGateSoundName(), 0, 0);
                    int result= (int) response.getData().getPassPersonSum();
                    Message message=new Message();
                    message.obj=result;
                    message.what=CHECK_SUCCESS;
                    mHandler.sendMessage(message);
                }else {
                    ShowMsg(response.getData().getGateSoundName(),0,0);
                }
            //   防止人工确认漏洞，置空
                m_strM1Card="";
                isCheck=false;
            }
        }).start();
    }
    /*
     * 人脸对比成功后检票
     * */
    private void checkTicketAfterCompare(final String typeData) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 先封装一个 JSON 对象
                JSONObject param = new JSONObject();

                try {
                    param.put("searchDataType", "1");
                    param.put("searchData", typeData);
                    param.put("checkCount", -1);
                    param.put("gateNo", m_strGateNo);
                    param.put("isCollectionGate", "Y");
                    param.put("ticketBarcodeId", response.getData().getTicketBarcodeId());
                    param.put("sign", "A96D48AE69F46BD0E1B17F10316086F3");
                    param.put("timestamp", "20180611165000");

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String ss = httpUtils.postJson(BaseUrl.checkTicketAfterComparison, param);
                QRCodeCheckResponse response = new Gson().fromJson(ss, QRCodeCheckResponse.class);
                if (response.getCode().equals("0")) {

                    ShowMsg(response.getData().getGateSoundName(), 0, 0);
                    int result= (int) response.getData().getPassPersonSum();
                    Message message=new Message();
                    message.obj=result;
                    message.what=CHECK_SUCCESS;
                    mHandler.sendMessage(message);
                }else {
                    ShowMsg(response.getData().getGateSoundName(), 0, 0);
                }
                // 防止人工确认漏洞，置空
                m_StrBarCode="";
                isCheck=false;
            }
        }).start();
    }

    /*
     * 获取IC卡采集信息
     * */
    private void getCheckCardCollection(final String ICCard) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 先封装一个 JSON 对象
                JSONObject param = new JSONObject();
                try {
                    param.put("cardTypeNo", ICCard);
                    param.put("sign", "");
                    param.put("timestamp", "");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String re = httpUtils.postJson(BaseUrl.getCheckCardCollection, param);
                cardCollectionResponse = new Gson().fromJson(re, ICCardCollectionResponse.class);

                if (cardCollectionResponse.getCode().equals("0")) {
                    tag_compare = 0;

                    base64.base64StrToImage(cardCollectionResponse.getData().get(0).getPhotoData(), m_FaceImgPath);
                    //显示图片
                    m_FaceBmp = pathUtils.GetBitmapByPath(m_FaceImgPath);
                    m_imageViewPhoto.post(new Runnable() {
                        @Override
                        public void run() {
                            m_imageViewPhoto.setImageBitmap(m_FaceBmp);
                        }
                    });
                    //获取成功人脸核验按钮开放
                    ShowMsg("图片获取成功", 0, 0);
                    m_btnFaceDetect.post(new Runnable() {
                        @Override
                        public void run() {
                            m_btnFaceDetect.setEnabled(true);
                        }
                    });
                }
            }
        }).start();
    }




    public void uploadICCardInfomation() {
        new Thread(new Runnable() {
            @Override
            public void run() {


            }
        }).start();
    }
    /*
     * 获取票采集信息
     * */
    public void getQRCodeCollection(final String typeData) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                // 先封装一个 JSON 对象
                JSONObject param = new JSONObject();
                try {
                    param.put("barcodeNo", typeData);
                    param.put("sign", "");
                    param.put("timestamp", "");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String re = httpUtils.postJson(BaseUrl.getCheckTicketCollection, param);

                qrCodeCollectionResponse = new Gson().fromJson(re, QRCodeCollectionResponse.class);

                if (qrCodeCollectionResponse.getCode().equals("0")) {
                    tag_compare = 1;
                    base64.base64StrToImage(qrCodeCollectionResponse.getData().getPhotoData(), m_FaceImgPath);
                    //显示图片
                    m_FaceBmp = pathUtils.GetBitmapByPath(m_FaceImgPath);

                    m_imageViewPhoto.post(new Runnable() {
                        @Override
                        public void run() {
                            m_imageViewPhoto.setImageBitmap(m_FaceBmp);
                        }
                    });

                    //获取成功人脸核验按钮开放
                    ShowMsg("图片获取成功", 0, 0);
                    m_btnFaceDetect.post(new Runnable() {
                        @Override
                        public void run() {
                            m_btnFaceDetect.setEnabled(true);
                        }
                    });
                }


            }
        }).start();
    }




    /**********************http请求**********************/

    /*
     * http请求(IC卡)
     */
    private void HttpURL(final int mode) {
        new Thread() {
            public void run() {
                send(mode);
            }
        }.start();
    }

    /*
     * 发送Http请求(IC卡)
     */
    public boolean send(int mode) {
        try {
            //检票模式
            if (mode == 0) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("CardNo", m_strM1Card);
                map.put("gateNo", m_strGateNo);
                String sign = signUtils.buildMysign(map, "zmdjfkgudjrhkhssnh");
                System.out.println(sign);
                String sendDate = "CardNo=" + m_strM1Card + "&gateNo=" + m_strGateNo + "&sign=" + sign;
                String result = httpUtils.sendPost(BaseUrl.checkCardNo, sendDate);
                LogUtil.d("result" + result);
                if (result.indexOf("<code>0</code>") > 0) {
                    //存储图片(并显示图片
                    String strbase64 = getxmlstr(result, "photoBase64Str");
                    m_strTicketNo = getxmlstr(result, "ticketNo");
                    base64.decoderBase64File(strbase64, m_FaceImgPath);
                    //显示图片
                    m_FaceBmp = pathUtils.GetBitmapByPath(m_FaceImgPath);

                    m_imageViewPhoto.post(new Runnable() {
                        @Override
                        public void run() {
                            m_imageViewPhoto.setImageBitmap(m_FaceBmp);
                        }
                    });
                    //获取成功人脸核验按钮开放
                    ShowMsg("图片获取成功", 0, 0);
                    //m_btnReadCard.setEnabled(true);

                    m_btnFaceDetect.post(new Runnable() {
                        @Override
                        public void run() {
                            m_btnFaceDetect.setEnabled(true);
                        }
                    });
                    //m_btnBarSacn.setEnabled(true);
                    SetBtnEnable(1);
                    m_btnOk.post(new Runnable() {
                        @Override
                        public void run() {
                            m_btnOk.setEnabled(true);
                        }
                    });

                } else {
                    ShowMsg("图片获取失败", 0, 0);
                    //m_btnFaceDetect.setEnabled(false);
                    //提示信息
                    String msg = getxmlstr(result, "message");

                    SetBtnEnable(1);
                    ToastUtil.showToast(msg);
                }
            } else {
                Map<String, String> map = new HashMap<String, String>();
                map.put("CardNo", m_strM1Card);
                map.put("gateNo", m_strGateNo);
                map.put("ticketNo", m_strTicketNo);
                String sign = signUtils.buildMysign(map, "zmdjfkgudjrhkhssnh");
                System.out.println(sign);
                String sendDate = "CardNo=" + m_strM1Card + "&gateNo=" + m_strGateNo + "&ticketNo=" + m_strTicketNo + "&sign=" + sign;
                String result = httpUtils.sendPost(BaseUrl.checkTicketReturnSave, sendDate);

                if (result.indexOf("<code>0</code>") > 0) {
                    //请通行
                    ShowMsg("请通行", 0, 0);
                    Log.d(TAG, "send: 11111111111");
                    mHandler.sendEmptyMessage(1);
                    String Date = getxmlstr(result, "dateTime");
                    ShowMsg(Date, 2, 0);

                    SetBtnEnable(1);
                } else {
                    //拒绝通行
                    ShowMsg("拒绝通行", 0, 0);
                    String Date = getxmlstr(result, "dateTime");
                    ShowMsg(Date, 2, 0);

                    SetBtnEnable(1);
                    //提示信息
                    String msg = getxmlstr(result, "message");
                    ToastUtil.showToast(msg);
                }
            }
        } catch (Exception e) {
            Log.d("card", "" + e.getMessage());
            // ToastUtil.showToast("请检查地址配置！");
            ToastUtil.showToast("系统异常11111111111111" + e.toString());
            SetBtnEnable(1);
            return false;
        }
        return true;
    }
    /*
     * http请求(二维码)
     */
    private void BarCodeHttpURL() {
        new Thread() {
            public void run() {
                BarCodeSend();
            }
        }.start();
    }

    /*
     * 发送Http请求(二维码)
     */
    public boolean BarCodeSend() {
        try {
            Map<String, String> map = new HashMap<String, String>();
            map.put("gateNo", m_strGateNo);
            map.put("ticketNo", m_StrBarCode);
            String sign = signUtils.buildMysign(map, "zmdjfkgudjrhkhssnh");
            System.out.println(sign);
            String sendDate = "TicketNo=" + m_StrBarCode + "&gateNo=" + m_strGateNo + "&sign=" + sign;
            String result = httpUtils.sendPost(BaseUrl.checkTicketByTicketNo, sendDate);

            String Code = getxmlstr(result, "code");

            if (Code.equals("0")) {

                String strResultCode = getxmlstr(result, "result");

                //需要采集
                if (strResultCode.equals("1")) {
                    ShowMsg("开始采集", 0, 0);
                    m_UpdatePhotoPath = getxmlstr(result, "photoPath");
                    m_UpdatePhotoName = getxmlstr(result, "photoName");
                    //开启采集模式
                    //启动采集模式的TakePhotoActivity
                    Intent intent = new Intent(this, TakePhotoActivity.class);
                    //Intent intent = new Intent(MainActivity.this,FaceTestActivity.class); //动态识别版 仅适用于V1算法
                    m_BGBmp = pathUtils.GetBitmapByPath(m_BgFacePath);
                    TakePhotoActivity.img = util.bitmap2ByteArray(m_BGBmp);
                    intent.putExtra("ALGORITHM_VERSION", ALGORITHM_VERSION);
                    intent.putExtra("WORKINGMODE", 2);
                    this.startActivityForResult(intent, 0);
                } else if (strResultCode.equals("2")) {
                    //二次入园
                    //保存图片
                    String strbase64 = getxmlstr(result, "photoBase64Str");
                    m_strTicketNo = getxmlstr(result, "ticketNo");
                    base64.decoderBase64File(strbase64, m_FaceImgPath);
                    //显示图片
                    m_FaceBmp = pathUtils.GetBitmapByPath(m_FaceImgPath);
                    m_imageViewPhoto.post(new Runnable() {
                        @Override
                        public void run() {
                            m_imageViewPhoto.setImageBitmap(m_FaceBmp);
                        }
                    });
                    SetBtnEnable(1);
                    //获取成功人脸核验按钮开放
                    ShowMsg("人脸图片获取成功", 0, 0);
                    m_btnOk.post(new Runnable() {
                        @Override
                        public void run() {
                            m_btnOk.setEnabled(true);
                        }
                    });
                } else if (strResultCode.equals("3")) {
                    //不需要采集
                    //直接放行
                    ShowMsg("有效票请通行", 0, 0);
                    Log.d(TAG, "send: 22222222222");
                    mHandler.sendEmptyMessage(1);

                    SetBtnEnable(1);
                } else if (strResultCode.equals("4")) {
                    //返回的提示信息
                    String msg_Error = getxmlstr(result, "msg");
                    if (msg_Error.indexOf(":") > 0) {
                        msg_Error = msg_Error.substring(msg_Error.indexOf(":") + 1);
                    }
                    ShowMsg(msg_Error, 0, 0);

                    SetBtnEnable(1);
                }

            } else {
                ShowMsg("检票失败", 0, 0);
                SetBtnEnable(1);
                //提示信息
                String msg = getxmlstr(result, "msg");
                ToastUtil.showToast(msg);
            }
        } catch (Exception e) {
            Log.d("excepion222", "" + e.getMessage());
            ToastUtil.showToast("系统异常22222222222");
            SetBtnEnable(1);
            return false;
        }
        return true;
    }

    /*
     * http请求(上传图片)
     */
    private void UpdateImgHttpURL() {
        new Thread() {
            public void run() {
                UpdateImgSend();
            }
        }.start();
    }

    /*
     * 发送Http请求(上传图片)
     */
    public boolean UpdateImgSend() {
        try {

            Map<String, String> map = new HashMap<String, String>();
            map.put("photoPath", m_UpdatePhotoPath);
            map.put("photoName", m_UpdatePhotoName);
            map.put("photoBase64str", m_UpdateBase64);
            String sign = signUtils.buildMysign(map, "zmdjfkgudjrhkhssnh");
            System.out.println(sign);
            String sendDate = "photoPath=" + m_UpdatePhotoPath + "&photoName=" + m_UpdatePhotoName + "&photoBase64str=" + m_UpdateBase64 + "&sign=" + sign;
            String result = httpUtils.sendPost(BaseUrl.checkTicketCollectReturn, sendDate);
            if (result.indexOf("<code>0</code>") > 0) {

                ShowMsg("上传成功", 0, 0);
                ShowMsg("请通行", 0, 0);
                Log.d(TAG, "send: 55555555555");
                mHandler.sendEmptyMessage(1);
                SetBtnEnable(1);

            } else {
                ShowMsg("上传失败", 0, 0);

                SetBtnEnable(1);
                //提示信息
                String msg = getxmlstr(result, "message");
                ToastUtil.showToast(msg);
            }
        } catch (Exception e) {
            // ToastUtil.showToast("请检查地址配置！");
            ToastUtil.showToast("系统异常3333333333");
            SetBtnEnable(1);
            return false;
        }
        return true;
    }

//    //非UI线程中显示Toast
//    public void showToast(String msg) {
//
//        Looper.prepare(); // No Looper is defined So define a new one
//
//        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
//        Looper.loop();
//    }

    @Override
    protected void onDestroy() {
        FaceHandle.getFaceSDKInstance(ALGORITHM_VERSION).deinit();
        super.onDestroy();
    }


}
